<?php


namespace App\Http\Controllers\Home;


use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use EasyWeChat\Factory;
use SimpleSoftwareIO\QrCode\Facades\QrCode;
use Illuminate\Support\Facades\Log;

class WechatController extends Controller
{
    private $payment;

    public function __construct()
    {
        $this->payment = Factory::payment(config('wechat.WECHAT.payment'));
    }

    /**
     * payScan 扫码支付
     * @return array
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function payScan()
    {
        $order_sn = date('YmdHis').str_shuffle(time());
        $total_fee  = env('NUOCHE_PRICE')*100;
        $order = $this->payment->order->unify([
            'trade_type'       => 'NATIVE',
            'body'             => '挪车码-订单支付',
            'out_trade_no'     => $order_sn,
            'total_fee'        => $total_fee
        ]);

        if ($order['result_code'] == 'SUCCESS') {
            return [
                'order_sn' => $order_sn,
                'total_fee'=>$total_fee,
                'html' => QrCode::format('png')->margin(0)->size(200)->generate($order['code_url'])
            ];
        }
    }

    /**
     * payJssdk 页面支付
     * @param string $openid
     * @return array
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function payJssdk($openid)
    {
        $order_sn = date('YmdHis').str_shuffle(time());
        $total_fee  = env('NUOCHE_PRICE')*100;
        $order = $this->payment->order->unify([
            'trade_type'       => 'JSAPI',
            'body'             => '挪车码-订单支付',
            'out_trade_no'     => $order_sn,
            'total_fee'        => $total_fee,
            'openid'           => $openid
        ]);
        if ($order['result_code'] == 'SUCCESS') {
            $json = $this->payment->jssdk->bridgeConfig($order['prepay_id']);
            return [
                'order_sn' => $order_sn,
                'total_fee'=>$total_fee,
                'json'     => $json
            ];
        }
    }



    /**
     * oauth 获取微信oauth
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function oauth(Request $request)
    {
        Log::info($request->getPathInfo());
        $app = Factory::officialAccount(config('wechat.WECHAT'));
        $oauth = $app->oauth;
        if (empty($request->session()->get('wechat_user')) && empty($request->get('code'))) {
            return $oauth->redirect();
        }

        if (Redis::get('wechat-code-'.$request->get('code'))){
            return $oauth->redirect();
        }else{
            Redis::setex('wechat-code-'.$request->get('code'), 10, $request->get('code'));
            session(['wechat_user' => $oauth->user()->toArray()]);
            $targetUrl = empty($request->session()->get('target_url'))?'/':$request->session()->get('target_url');
            header('location:'. $targetUrl);
        }
    }

    /**
     * JSSDK 分享接口
     * @return array|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function JSSDK()
    {
        $app = Factory::officialAccount(config('wechat.WECHAT'));
        $json = $app->jssdk->buildConfig(['checkJsApi','onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ','onMenuShareQZone'],false);
        return $json;
    }

    /**
     * notify 微信支付回调
     * @return bool|\Symfony\Component\HttpFoundation\Response
     * @throws \EasyWeChat\Kernel\Exceptions\Exception
     */
    public function notify()
    {
        $response = $this->payment->handlePaidNotify(function($message, $fail){
            Log::info($message);
            $is_pay = DB::table('pay_logs')->where('trade_no',$message['out_trade_no'])->value('state');
            if ($is_pay) {
                return true;
            }
            // return_code 表示通信状态，不代表支付状态
            if ($message['return_code'] === 'SUCCESS') {
                // 用户是否支付成功
                if ($message['result_code'] === 'SUCCESS') {
                    DB::transaction(function () use ($message,$logs) {
                        //主要业务写在这儿
                    });
                    $this->payMessage($logs['0']->openid,$message['out_trade_no'],$message['total_fee']/100,($message['total_fee'] * env('NUOCHE_COMMISSION_RATE'))/100);
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }
            return true;
        });
        return $response;
    }

    /**
     * redpack 发红包（备用）
     * @param $openid
     * @param $amount
     * @return array
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    private function redpack($openid,$amount)
    {
        $redpackData = [
            'mch_billno'   => date('YmdHis').str_shuffle(time()),
            'send_name'    => '挪车码返利',
            're_openid'    => $openid,
            'total_amount' => $amount,  //单位为分，不小于100
            'wishing'      => '感谢谢您的付出',
            'act_name'     => '挪车码返利',
            'remark'       => '百车网',
        ];
        return $this->payment->redpack->sendNormal($redpackData);
    }

    /**
     * mchPay 企业付款到用户零钱
     * @param $openid
     * @param $amount
     * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    private function mchPay($openid,$amount)
    {
        return $this->payment->transfer->toBalance([
            'partner_trade_no' => date('YmdHis').str_shuffle(time()),
            'openid' => $openid,
            'check_name' => 'NO_CHECK', // NO_CHECK：不校验真实姓名, FORCE_CHECK：强校验真实姓名
            're_user_name' => '小卢', // 如果 check_name 设置为FORCE_CHECK，则必填用户真实姓名
            'amount' => $amount, // 企业付款金额，单位为分
            'desc' => '挪车码收入', // 企业付款操作说明信息。必填
        ]);
    }

    /**
     * payMessage 发送支付成功信息
     * @param $openid
     * @param $trade_no
     * @param $money
     * @param $msgRedpackt
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    private function payMessage($openid,$trade_no,$money,$msgRedpackt)
    {
        $app = Factory::officialAccount(config('wechat.WECHAT'));
        $app->template_message->send([
            'touser' => $openid,
            'template_id' => '1-rKRh7_WggeP-1D-KG3x8lwn1Dh8l3JJw2rOi7Gk3o',
            'url' => 'https://sp.baiche.com.cn/v1/nuoche/sales/',
            'data' => [
                'first' => '恭喜,您有新订单已支付成功！您获得'.$msgRedpackt.'元奖励!再接再厉!',
                'keyword1' => $trade_no,
                'keyword2' => '￥'.$money,
                'keyword3' => date('Y-m-d H:i:s'),
                'remark' => '更多信息，请在会员中心查看。'
            ],
        ]);

    }
}
